package com.rookie.springcloud.eurekaclientthirdhystrix.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.rookie.springcloud.eurekaclientthirdhystrix.service.DeptService;
import com.rookie.springcloud.miscroserviceapi.entities.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author linhaiping
 * date 2020-02-29
 */
@RestController
public class EurekaClientController {

    @Autowired
    private DeptService service;

    @PostMapping(value = "/dept/add")
    public boolean add(@RequestBody Dept dept) {
        return service.add(dept);
    }

    /**
     * 熔断机制
     * 当方法抛出一场之后，调用备用方法返回预期响应
     * <p>
     * 直接加在客户端，导致代码高耦合
     * 交给接口处理
     */
    @GetMapping(value = "/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "processHystrix")
    public Dept get(@PathVariable("id") Long id) {

        /**
         * 模拟服务抛异常出错
         * **/
        if (id > 5) {
            throw new RuntimeException("模拟异常");
        }
        return service.get(id);
    }

    public Dept processHystrix(@PathVariable("id") Long id) {
        return new Dept().setDeptno(id)
                .setDname("该id没有对应的信息")
                .setDbSource("没有对应的数据库");
    }

    @GetMapping(value = "/dept/list")
    public List<Dept> list() {
        return service.list();
    }

}
